const http = require('http');
const resolveUrl = require('url');
const path = require('path')
const fs = require('fs');
const querystring = require('querystring');
const PORT = 9999;

const MIME = {
  "html": "text/html",
  "js": "text/javascript",
  "css": "text/css",
  "jpg": "image/jpeg",
  "ico": "image/x-icon"
}

const server = http.createServer((req, res) => {

  // 1. 读文件
  // 后缀  .html  .js  .css
  const url = req.url;
  const pathname = resolveUrl.parse(url).pathname;
  const extname = path.extname(pathname);

  const contentype = MIME[extname.slice(1)] || 'text/plain'
  const filePath = path.join(__dirname, 'public', pathname)
  const method = req.method;
  console.log(filePath, 'filePath')
  // 接收get参数 
  // http://localhost:9999/api/register?name=devin&pwd=123
  req.query = querystring.parse(url.split('?')[1])

  if (extname) {
    if (extname === '.ico') {
      res.end('111')
      return;
    }
    // 响应头
    res.writeHead(200, {
      "content-type": `${contentype};charset=UTF-8`
    });
    //建立流对象，读文件
    var stream = fs.createReadStream(filePath);
    //读取文件
    stream.pipe(res);
    return;
  } else {
    res.writeHead(200, {
      'Content-type': "text/json"
    })
    // 2. 写接口
    // api/login  api/register
    if (method === 'GET' && pathname === '/api/login') {
      res.end('/login')
    }
    if (method === 'GET' && pathname === '/api/register') {
      // 1. 接收参数
      console.log(req.query, 'req.query')
      // 2. 判断参数 数据中是否已经注册
      // 3. 如果已经注册，让他登陆
      // 4. 如果未注册，把账号密码写入文件
      res.end('/register')
    }
    res.end('接口')
    return;
  }
})

server.listen(PORT, () => {
  console.log(`server port is ${PORT}`)
})